import React from "react";
import {
  NavLink,
  Route,
  Routes,
  useParams,
  useLocation,
  useSearchParams,
  useMatch,
  useNavigate,
} from "react-router-dom";

const fruits = [
  { id: 1, name: "苹果", price: 100 },
  { id: 2, name: "香蕉", price: 200 },
  { id: 3, name: "橘子", price: 300 },
];

function FruitInfo() {
  const { id } = useParams();
  const info = fruits.find((item) => item.id === +id);
  return (
    <div>
      <h2>水果详情</h2>
      <p>id: {info.id}</p>
      <p>name: {info.name}</p>
      <p>price: {info.price}</p>
    </div>
  );
}

function App() {
  const navigate = useNavigate();

  function go(id) {
    // 编程式导航来跳转
    //    v5中使用 props.history.push replace go goBack goForward
    //    v6中没有这个 history 了。需要使用 useNavigate 的 hook 来使用
    //    useNavigate()  => navigate 的函数
    //      navigate(to, options)
    //          options = { replace  state }

    // 传递第二个参数 ，replace 为 true, 跳转将会是 replace 模式
    navigate(`/fruit-detail/${id}`, { replace: true });
  }

  return (
    <div className="app">
      <div className="header">卖水果咯</div>
      <div className="main">
        <div className="left">
          <ul>
            {fruits.map((item) => {
              return (
                <li key={item.id}>
                  <NavLink className="link" to={`/fruit-detail/${item.id}`}>
                    {item.name}
                  </NavLink>
                </li>
              );
            })}
          </ul>

          {fruits.map((item) => {
            return (
              <button
                key={item.id}
                onClick={() => {
                  go(item.id);
                }}
              >
                点我跳转到 {item.name}
              </button>
            );
          })}
        </div>
        <div className="right">
          <Routes>
            <Route path="/fruit-detail/:id" element={<FruitInfo />}></Route>
          </Routes>
        </div>
      </div>
    </div>
  );
}

export default App;
